Step 20: Query Parameters

There is a common pattern when making GET requests that I have not explored yet. It is filtering or searching among the collection of a resource by providing “query parameters.” For example, suppose we want to search for all bookmarks that include a particular keyword in their title. You would make this request as follows:

GET {{BASE_URL}}/bookmarks?title={{KEYWORD}}

The part title={{KEYWORD}} is a query string. It is a part of a URL that assigns values to specified parameters. The question mark is used as a separator, and is not part of the query string. Multiple parameters in the query string can be provided separated by & delimiter.

For this scenario, we expect a client to use the same endpoint as the one to get all bookmarks but optionally provide a search query parameter.

HTTP MethodGET
API Endpoint/bookmarks
Request Path Parameter
Request Query Parametertitle, url
Request Body
Response BodyJSON array of bookmarks
Response Status200

We can update the route handler we already have in src/routes/bookmarks.js to account for this scenario:

router.get("/bookmarks", (req, res) => {
  const { title, url } = req.query;
  const bookmarks = bookmarkDao.readAll({ title, url });
  res.json({
    status: 200,
    message: `Successfully retrieved ${bookmarks.length} bookmarks!`,
    data: bookmarks
  });
});

Notice I have used the req.query object to get the query parameter (instead of using req.params for getting path parameters).

Moreover, notice how I pass these parameters to the readAll function of the Bookmark DAO. We should update that function (in src/data/BookmarkDAO.js) to account for this case:

// return all bookmarks
readAll({ title, url }) {
  let bookmarks = this.bookmarks;

  if (title) {
    bookmarks = bookmarks.filter((bookmark) => bookmark.title === title);
  }

  if (url) {
    bookmarks = bookmarks.filter((bookmark) => bookmark.url === url);
  }

  return bookmarks;
}

Run the API server and make a few bookmarks using Postman. Employ a common title for some of them. Then, make a Postman request with a title query parameter to search for those bookmarks.

Untitled

Save and commit all changes.